import { ModbusReg } from "@/services/equip-socket/types/SocketData";
import { bytesToShort, bytetou16, hexStringToBytes } from "./conversion";

// ai、ao的线性转换
export const regAIAOParse = ({ value, fX1 = 0, fY1 = 0, fX2 = 0, fY2 = 0 }: { value: number; fX1: number; fY1: number; fX2: number; fY2: number }) => {
    let res = value;
    if (fX1 != fX2 && fY1 != fY2) res = fY1 + ((fY2 - fY1) * (value - fX1)) / (fX2 - fX1);
    return res;
};
// ai、ao的逆线性转换
export const regAIAOInverseParse = ({ value, fX1 = 0, fY1 = 0, fX2 = 0, fY2 = 0 }: { value: number; fX1: number; fY1: number; fX2: number; fY2: number }) => {
    return regAIAOParse({ value, fX1: fY1, fY1: fX1, fX2: fY2, fY2: fX2 });
};
// 解析regdi或regdo数组为16位的2进制数
export const regDIDOParse = ({ num, regData }: { num: number; regData: number[] }) => {
    let dido: number[] = [];
    if (regData.length < num >> 3) return dido;
    for (let i = 0; i < num; i++) dido[i] = regData[i >> 3] & (1 << (i & 0x07)) ? 1 : 0;
    return dido;
};
// 解析ws返回的aomodbus原始数据
export const aoModbusRegParse = (modbusRegData: ModbusReg) => {
    let regnum = modbusRegData.regnum;
    let regAO = [];
    let tm = hexStringToBytes(modbusRegData.strinfo.substring(6, 6 + regnum * 4));
    for (let i = 0; i < modbusRegData.regnum; i++) regAO[i] = bytesToShort(tm, 2 * i);
    return regAO;
};
export const adjustAIParse = (modbusRegData: ModbusReg) => {
    let src = hexStringToBytes(modbusRegData.strinfo.substring(6, 6 + modbusRegData.regnum * 4));
    let res = [];
    for (let i = 0; i < modbusRegData.regnum / 3; i++) {
        res[i] = { mode: bytetou16(src, i * 6), down: bytetou16(src, i * 6 + 2), up: bytetou16(src, i * 6 + 4) };
    }
    return res;
};
